use env_logger::Env;
use ntex::web::{self, get, middleware, App, HttpResponse, HttpServer, Responder};
use ntex_admin::handle::admin::system_admin::system_admin;
use ntex_admin::handle::admin::system_admin_auth::system_admin_auth;
use ntex_admin::handle::common::captcha::captcha;
use ntex_admin::{middleware::auth::Auth, APPLICATION_CONTEXT};
use ntex_cors::Cors;
use ntex_files::Files;

#[get("/")]
async fn index() -> impl Responder {
    HttpResponse::Ok().body("Ntex-Admin V1.0")
}

#[ntex::main]
async fn main() -> std::io::Result<()> {
    // 初始化系统
    ntex_admin::startup().await;
    // 开启日志
    env_logger::init_from_env(Env::default().default_filter_or("info"));
    // 获取Context
    let context = &APPLICATION_CONTEXT;
    // 启动系统服务
    HttpServer::new(|| {
        App::new()
            .wrap(middleware::Logger::default())
            .wrap(middleware::Logger::new("%a %{User-Agent}i"))
            .wrap(Auth)
            .wrap(Cors::default())
            .service(index)
            .service(
                web::scope("/api")
                    .configure(system_admin_auth)
                    .configure(system_admin)
                    .configure(captcha),
            )
            .service(
                Files::new("/static", "./static")
                    .show_files_listing()
                    .use_last_modified(true),
            )
    })
    .bind((
        context.config.server_url.to_owned(),
        context.config.port.to_owned(),
    ))?
    .run()
    .await
}
